package com.ruoyi.odorservice.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.odorservice.entity.Sample;
import com.ruoyi.odorservice.entity.SampleDetail;
import com.ruoyi.odorservice.entity.StandardFiles;
import com.ruoyi.odorservice.model.bean.CompanyIndustryInfoBean;
import com.ruoyi.odorservice.service.SampleDetailService;
import com.ruoyi.odorservice.service.SampleService;
import com.ruoyi.odorservice.utils.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sample")
@Api(tags = "样本")
@AllArgsConstructor
public class SampleController extends BaseController {
    private SampleService sampleService;
    private SampleDetailService sampleDetailService;

    @PostMapping("/delete/{id}")
    @ApiOperation(value = "删除样本",httpMethod = "POST", response = StandardFiles.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "样本ID", paramType = "path", dataType = "Integer")
    })
    public Result delete(@PathVariable(value ="id") Integer id) {
        if (sampleService.removeById(id)){
            sampleDetailService.remove(new LambdaQueryWrapper<SampleDetail>()
                    .eq(SampleDetail::getSampleId,id));
            return Result.ok();
        }
        else
            return Result.fail();
    }

    @PostMapping("/update/{id}")
    @ApiOperation(value = "更新样本详情",httpMethod = "POST", response = StandardFiles.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "样本详情ID", paramType = "path", dataType = "Integer")
    })
    public Result update(@PathVariable(value ="id") Integer id,
                             @RequestBody SampleDetail sampleDetail) {
        sampleDetail.setId(id);
        assert sampleDetail.getSampleId() != null;
        if (sampleDetailService.updateById(sampleDetail))
            return Result.ok();
        else
            return Result.fail();
    }

    @GetMapping("/pages")
    @ApiOperation(value = "样本分页查询",httpMethod = "GET", response = StandardFiles.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Integer" , required = false),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Integer" , required = false),
            @ApiImplicitParam(name = "siteName", value = "样本名称", paramType = "query", dataType = "String", required = false)
    })
    public TableDataInfo pages(@RequestParam(value ="page", defaultValue = "1", required = false) Integer page,
                               @RequestParam(value ="limit", defaultValue = "10", required = false) Integer limit,
                               @RequestParam(value = "siteName", required = false) String siteName) {
        startPage();
        List<Sample> list = sampleService.list(new LambdaQueryWrapper<Sample>()
                .like(StrUtil.isNotEmpty(siteName),Sample::getSiteName,siteName));
        return getDataTable(list);
    }

    @GetMapping("details/pages")
    @ApiOperation(value = "样本详情分页查询",httpMethod = "GET", response = StandardFiles.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Integer" , required = false),
            @ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Integer" , required = false),
            @ApiImplicitParam(name = "sampleId", value = "样本ID", paramType = "query", dataType = "String", required = false)
    })
    public TableDataInfo details(@RequestParam(value ="page", defaultValue = "1", required = false) Integer page,
                               @RequestParam(value ="limit", defaultValue = "10", required = false) Integer limit,
                               @RequestParam(value = "sampleId", required = false) String sampleId) {
        startPage();
        List<SampleDetail> list = sampleDetailService.list(new LambdaQueryWrapper<SampleDetail>()
                .like(SampleDetail::getSampleId,sampleId));
        return getDataTable(list);
    }

    @GetMapping("details/{sampleId}")
    @ApiOperation(value = "样本详情（谱）",httpMethod = "GET", response = StandardFiles.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sampleId", value = "样本ID, 616默认敏感点样本ID", defaultValue = "616",paramType = "path", dataType = "String", required = false)
    })
    public Result<List<SampleDetail>> detail(@PathVariable(value = "sampleId") String sampleId) {
        List<SampleDetail> list = sampleDetailService.list(new LambdaQueryWrapper<SampleDetail>()
                .eq(SampleDetail::getSampleId,sampleId));
        return Result.ok(list);
    }

    @ApiOperation(value = "上传样本", httpMethod="POST" ,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", paramType="form", value = "文件", dataType="file", required = true),
    })
    @PostMapping(value = "/importExcel")
    @ResponseBody
    public Result importExcel(@RequestPart @RequestParam("file") MultipartFile file){
        LocalDateTime now = LocalDateTime.now();
        try (InputStream inputStream = file.getInputStream()) {
            Map<String,String[][]> map =  ExcelUtils.readExcel(inputStream);
            assert map != null;
            map.forEach((k, v)->{
                int rows = v.length;
                int cols = (rows > 0) ? v[0].length : 0;
                for (int i = 1; i < cols; i++) {
                    Sample sample = new Sample();
                    sample.setSiteName(k);
                    sample.setCreateTime(now);
                    sample.setSampleTime(LocalDateTime.parse(v[0][i],DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    sampleService.save(sample);
                    List<SampleDetail> list = new ArrayList<>();
                    for (int j = 1; j < rows; j++) {
                        SampleDetail sampleDetail = new SampleDetail();
                        sampleDetail.setSampleId(sample.getId());
                        sampleDetail.setMaterialName(v[j][0]);
                        try {
                            sampleDetail.setConcentration(StrUtil.isNotBlank(v[j][i])?Double.parseDouble(v[j][i]):0);
                        }catch (Exception e){
                            sampleDetail.setConcentration(-1.0);
                        }
                        list.add(sampleDetail);
                    }
                    sampleDetailService.saveBatch(list);
                }
            });
            return Result.ok("上传成功！");
        } catch (IOException e) {
            return Result.fail("上传失败！");
        }
    }
}
